var co = require('co');
var seqModule = require('../../../routes/createModules');
var seq = new seqModule();
var util = require('../../../common/util');
var EventProxy = require('eventproxy');
var _ = require('lodash');
var formidable = require('formidable');
var fs = require('fs');
var moment = require("moment");
var util1 = require('util');
var unzip = require('unzip');

var blController = {
    getListPage: function (req, res) {
        var params = {};
        var paramT = {};
        if (req.query.item != undefined) {
            params.item = parseInt(req.query.item);
        }
        if (req.query.sort != undefined) {
            params.sort = parseInt(req.query.sort);
        }
        if (req.query.type != undefined) {
            params.type = parseInt(req.query.type);
        }
        if (req.query.pTitle != undefined) {
            params["$or"] = [{ "title": { "$like": '%' + req.query.pTitle + '%' } }, { "expertName": { "$like": '%' + req.query.pTitle + '%' } }]
        }
        var page = req.query.page;
        paramT.where = params;
        paramT.order = [["topTime", "DESC"]];
        var page = parseInt(req.query.page);
        if (req.query.page != undefined && req.query.rows != undefined) {
            paramT["offset"] = parseInt(req.query.page);
            paramT["limit"] = parseInt(req.query.rows);
        }
        seq.bingliModule.findAndCountAll(paramT).then(function (result) {
            res.json({
                'success': true, 'msg': '查询成功！', 'total': result.count, 'page': page, 'result': result.rows
            });
        }).catch(function (err) {
            res.json({ 'success': false, 'msg': '查询失败' });
            console.log(err);
        })
    },
    getblById: function (req, res) {
        if (_.isEmpty(req.params) || !_.hasIn(req.params, 'id') || _.isEmpty(req.params.id)) {
            res.json({ 'success': false, 'msg': 'ID未传参！' });
        } else {
            seq.bingliModule.findOne({ where: req.params }).then(function (result) {
                res.json({ 'success': true, 'msg': '查询成功！', 'result': result });
            }).catch(function (err) {
                res.json({ 'success': false, 'msg': '查询失败' });
                console.log(err);
            });
        }
    },
    addBls: function (req, res) {
        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            form.uploadDir = "public/data/";
            //files = [],
            //fields = []
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                if (files.expertHeadimg != null && files.expertHeadimg.name != "") {
                    var imgType = files.expertHeadimg.name.split(".");
                    files.expertHeadimg.name = "blExpert_" + moment().format("YYYYMMDDHHmmss") + "." + imgType[imgType.length - 1];
                    fs.renameSync(files.expertHeadimg.path, form.uploadDir + "expertImg/" + files.expertHeadimg.name);
                    fields.expertHeadimg = files.expertHeadimg.name;
                }
                if (files.titlePic != null && files.titlePic.name != "") {
                    var coverType = files.titlePic.name.split(".");
                    files.titlePic.name = "blCover_" + moment().format("YYYYMMDDHHmmss") + "." + coverType[coverType.length - 1];
                    fs.renameSync(files.titlePic.path, form.uploadDir + "blCover/" + files.titlePic.name);
                    fields.titlePic = files.titlePic.name;
                }
                if (fields.attachType == 2 && files.attachPPT.name != "") {
                    var sourcePath = files.attachPPT.path;
                    var uploadImgUrl = files.attachPPT.name;
                    var uploadImgCount = uploadImgUrl.substring(uploadImgUrl.lastIndexOf("_") + 1, uploadImgUrl.lastIndexOf("."));
                    var imgName = "blPic" + moment().format("YYYYMMDDHHmmss") + "_" + uploadImgCount;
                    fs.createReadStream(sourcePath).pipe(unzip.Extract({ path: form.uploadDir + "blPic/" + imgName }));
                    fields.attachPPT = imgName;
                }
                fields.id = util.getUUID();
                fields.createTime = util.getNowTime();
                fields.topTime = util.getNowTime();
                var item = parseInt(fields.item);
                var sort = parseInt(fields.sort);
                seq.bingliModule.create(fields).then(function (result) {
                    if (item == 3) {
                        res.redirect(util.getIP() + 'wzzTime/wzzBlList.html?item=' + item + '&sort=' + sort);
                    } else {
                        res.redirect(util.getIP() + 'nxgTime/nxgBlList.html?item=' + item + '&sort=' + sort);
                    }

                })
            });
        } else {
            console.log("请求方式不正确");
        }
    },
    updateBls: function (req, res) {
        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            //files = [],
            //fields = [];
            form.uploadDir = "public/data/";
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                var paramT = {};
                if (files.expertHeadimg != null && files.expertHeadimg.name != "") {
                    var imgType = files.expertHeadimg.name.split(".");
                    files.expertHeadimg.name = "blExpert_" + moment().format("YYYYMMDDHHmmss") + "." + imgType[imgType.length - 1];
                    fs.renameSync(files.expertHeadimg.path, form.uploadDir + "expertImg/" + files.expertHeadimg.name);
                    fields.expertHeadimg = files.expertHeadimg.name;
                }
                if (files.titlePic != null && files.titlePic.name != "") {
                    var coverType = files.titlePic.name.split(".");
                    files.titlePic.name = "blCover_" + moment().format("YYYYMMDDHHmmss") + "." + coverType[coverType.length - 1];
                    fs.renameSync(files.titlePic.path, form.uploadDir + "blCover/" + files.titlePic.name);
                    fields.titlePic = files.titlePic.name;
                }
                if (fields.attachType == 2 && files.attachPPT.name != "") {
                    var sourcePath = files.attachPPT.path;
                    var uploadImgUrl = files.attachPPT.name;
                    var uploadImgCount = uploadImgUrl.substring(uploadImgUrl.lastIndexOf("_") + 1, uploadImgUrl.lastIndexOf("."));
                    var imgName = "blPic" + moment().format("YYYYMMDDHHmmss") + "_" + uploadImgCount;
                    fs.createReadStream(sourcePath).pipe(unzip.Extract({ path: form.uploadDir + "blPic/" + imgName }));
                    fields.attachPPT = imgName;
                }
                var item = parseInt(fields.item);
                var sort = parseInt(fields.sort);
                paramT.where = req.params;
                seq.bingliModule.update(fields, paramT).then(function (result) {
                    if (item == 3) {
                        res.redirect(util.getIP() + 'wzzTime/wzzBlList.html?item=' + item + '&sort=' + sort);
                    } else {
                        res.redirect(util.getIP() + 'nxgTime/nxgBlList.html?item=' + item + '&sort=' + sort);
                    }
                })
            });
        } else {
            console.log("请求方式不正确");
        }
    },
    deleteBl: function (req, res) {
        var params = req.query.params;
        var arr = params.split(",");
        var paramT = [arr];
        seq.bingliModule.destroy({ 'where': { 'id': paramT } }).then(function (results) {
            res.json({ "success": true, "msg": "删除成功", "result": results });
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '删除失败' });
            console.log(e);
        })
    },
    blSetTop: function (req, res) {
        var nowTime = util.getNowTime();
        seq.bingliModule.update({ "topTime": nowTime }, { where: req.params }).then(function (result) {
            res.json({ "success": true, "msg": "修改成功" });
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '修改失败' });
            console.log(e);
        })
    }
}
module.exports = blController;